package cn.rkylin.oms.salespromotion.rules.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.rkylin.oms.salespromotion.rules.util.handler.RuleMatchHandler;
import cn.rkylin.oms.salespromotion.rules.util.handler.impl.ConstrainGoodsHandler;
import cn.rkylin.oms.salespromotion.rules.util.handler.impl.EachDayCheckHandler;
import cn.rkylin.oms.salespromotion.rules.util.handler.impl.OrderAmountConstrainHandler;
import cn.rkylin.oms.salespromotion.rules.util.handler.impl.ShopConstrainHandler;
import cn.rkylin.oms.salespromotion.rules.util.stretegy.AbstractGiftCaculateStretegy;
import cn.rkylin.oms.salespromotion.rules.util.stretegy.IGiftCaculateStretegy;
import cn.rkylin.oms.salespromotion.rules.util.stretegy.impl.GoodsKindsCaculator;
import cn.rkylin.oms.salespromotion.rules.util.stretegy.impl.GoodsPieceCaculator;
import cn.rkylin.oms.salespromotion.rules.util.stretegy.impl.OrderAmountCaculator;
import cn.rkylin.oms.salespromotion.rules.vo.SalesPromotionRuleVO;

public class GiftCaculatorUtil {
    
    private GiftCaculatorUtil() {
        
    }
    
    public static RuleMatchHandler getRuleMatchHandlr() {
        // 定义责任链节点-金额校验
        RuleMatchHandler orderAmountConstrainHandler = new OrderAmountConstrainHandler();
        // 定义责任链节点-店铺校验
        RuleMatchHandler shopConstrainHandler = new ShopConstrainHandler();
        // 定义责任链节点-限制商品校验
        RuleMatchHandler constrainGoodsHandler = new ConstrainGoodsHandler();
        // 定义责任链节点-每日时间段校验
        RuleMatchHandler eachDayCheckHandler = new EachDayCheckHandler();
        
        // 组装责任链
        orderAmountConstrainHandler.SetSuccessor(eachDayCheckHandler);
        eachDayCheckHandler.SetSuccessor(shopConstrainHandler);
        shopConstrainHandler.SetSuccessor(constrainGoodsHandler);
        
        return orderAmountConstrainHandler;
    }
    
    /**
     * getCaculateStretegy:根据规则对象获取规则计算对象. <br/>
     *
     * @author zhanghao
     * @param ruleVO
     * @return
     */
    public static IGiftCaculateStretegy getCaculateStretegy(SalesPromotionRuleVO ruleVO) {
        IGiftCaculateStretegy caculateStretegy = null;
        JSONObject jsonObject = JSONObject.parseObject(ruleVO.getPresentCaculateRule());
        JSONArray segments = jsonObject.getJSONArray("segments");
        JSONObject segment = segments.getJSONObject(0); 
        String unittype = (String) jsonObject.get("unit");
        
        // 根据规则内容返回规则匹配的赠品列表
        if(unittype.equalsIgnoreCase(AbstractGiftCaculateStretegy.CACULATE_BY_GOODS_KIND)) {
            caculateStretegy = new GoodsKindsCaculator();
        }else if(unittype.equalsIgnoreCase(AbstractGiftCaculateStretegy.CACULATE_BY_GOODS_PIECE)) {
            caculateStretegy = new GoodsPieceCaculator();
        }else if(unittype.equalsIgnoreCase(AbstractGiftCaculateStretegy.CACULATE_BY_ORDER_AMOUNT)) {
            caculateStretegy = new OrderAmountCaculator();
        }
        return caculateStretegy;
    }
}
